//
//  MemberCardRecordsViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 16/3/24.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "MemberCardRecordsViewController.h"
#import "TheLoginViewController.h"
#import "MemberCardTopUpViewController.h"

@interface MemberCardRecordsViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)UIDatePicker* da;

@end

@implementation MemberCardRecordsViewController

{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*orderid;
    NSMutableArray*gtype;
    NSMutableArray*amount;
    NSMutableArray*status;
    NSMutableArray*createDate;
    int pageNumber;
    BOOL saveAccount;
    UITableView *table;
    UIView*tableHeaderView;
    NSDictionary*dic;
}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    [self setNavi];
    [self requestData];
 
}

-(void)add:(UIButton*)sender{
    MemberCardTopUpViewController *detailViewController = [[MemberCardTopUpViewController alloc] init];
    detailViewController.memberId=self.memberId;
    detailViewController.userName=self.userName;
    detailViewController.phone=self.phone;
    [self.navigationController pushViewController:detailViewController animated:YES];
 
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self addFooter];
    [self addheader];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];

}
-(void)requestData{
    
    pageNumber = 1;
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.memberId forKey:@"memberId"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Business/Member/CardRecords" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                dic=severDataDict.dataDict;
               [self tableHeaderView];
                orderid= [[NSMutableArray alloc] init];
                status= [[NSMutableArray alloc] init];
                amount= [[NSMutableArray alloc] init];
                createDate = [[NSMutableArray alloc] init];
                gtype= [[NSMutableArray alloc] init];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                  
                    [orderid addObject:[dicc valueForKey:@"orderId"]];
                    [amount addObject:[dicc valueForKey:@"amount"]];
                    [status addObject:[dicc valueForKey:@"status"]];
                    [createDate addObject:[dicc valueForKey:@"createDate"]];
                    [gtype addObject:[dicc valueForKey:@"gtype"]];
                    
                    
                    
                }
                [table reloadData];
                
            }else{
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
}
//上拉刷新
- (void)addFooter
{
    
    
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token ==nil) {
            Token=@"dd";
        }
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        [param setValue:self.memberId forKey:@"memberId"];
        [param setValue:@"20" forKey:@"pageSize"];
        [param setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
        //NSLog(@"====%@",param);
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        [HttpRequest requestData:@"Business/Member/CardRecords" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    for (NSDictionary* dicc in arrr )
                    {
                        [orderid addObject:[dicc valueForKey:@"orderId"]];
                        [amount addObject:[dicc valueForKey:@"amount"]];
                        [status addObject:[dicc valueForKey:@"status"]];
                        [createDate addObject:[dicc valueForKey:@"createDate"]];
                        [gtype addObject:[dicc valueForKey:@"gtype"]];

                    }
                    [table reloadData];
                    
                }else{
                    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        
                        TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                        [self.navigationController pushViewController:detailViewController animated:YES];
                    }
                }
                
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
            
        }];
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
   
    return [gtype count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    UILabel*titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 20, ScreenWidth-110,15)];
    if ([[gtype objectAtIndex:indexPath.row]isEqualToString:@"1"]) {
        titleLabel.text=[NSString stringWithFormat:@"%@",  @"储值卡充值"];}
    if ([[gtype objectAtIndex:indexPath.row]isEqualToString:@"2"]) {
        titleLabel.text=[NSString stringWithFormat:@"%@",  @"购买商品"];
    }
    titleLabel.font=[UIFont systemFontOfSize:15];
    [cell.contentView addSubview:titleLabel];
    NSRange range={0,16};
    NSString* string =[[NSString stringWithFormat:@"%@",[createDate objectAtIndex:indexPath.row]] substringWithRange:range];
    UILabel*timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 40, 200,12)];
    timeLabel.text =[NSString stringWithFormat:@"%@", string];
    timeLabel.font=[UIFont systemFontOfSize:12];
    timeLabel.textColor=zhonghuiColor;
    [cell.contentView addSubview:timeLabel];
    NSString*GoldPrice=[NSString stringWithFormat:@"%@",[amount objectAtIndex:indexPath.row]];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:GoldPrice.floatValue]];
    UILabel*priceLabel=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-80, 20, 65,18)];
    priceLabel.text =[NSString stringWithFormat:@"￥%@",  formattedNumberString];
    priceLabel.font=[UIFont systemFontOfSize:18];
    priceLabel.textAlignment=NSTextAlignmentRight;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"￥%@",  formattedNumberString]];
        
        [AttributedStr addAttribute:NSFontAttributeName
         
                              value:[UIFont systemFontOfSize:14.0]
         
                              range:NSMakeRange(0, 1)];
        
        [AttributedStr addAttribute:NSForegroundColorAttributeName
         
                              value:[UIColor blackColor]
         
                              range:NSMakeRange(0, 1)];
       priceLabel.attributedText = AttributedStr;
       [cell.contentView addSubview:priceLabel];
    
    UILabel*statusLabel=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-200, 40, 185, 12)];
    statusLabel.textAlignment=NSTextAlignmentRight;
    statusLabel.font=[UIFont systemFontOfSize:12];
    if ([[status objectAtIndex:indexPath.row]isEqualToString:@"Y"]) {
           statusLabel.text =[NSString stringWithFormat:@"%@",@"交易成功"];
            statusLabel.textColor=shenhuiColor;
        }else{
           statusLabel.text =[NSString stringWithFormat:@"%@",@"交易失败"];
            statusLabel.textColor=hongseColor;
        }
    [cell.contentView addSubview:statusLabel];
        
    if (createDate.count !=indexPath.row+1) {
            UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(15, 80-0.35, ScreenWidth-30, 0.35)];
            lineLabel1.backgroundColor=qianhuiColor;
            [cell.contentView addSubview:lineLabel1];
            
        }
        
        if (createDate.count ==indexPath.row+1) {
            UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(0, 80-0.35, ScreenWidth, 0.35)];
            lineLabel1.backgroundColor=qianhuiColor;
            [cell.contentView addSubview:lineLabel1];
            
        }
    
    
    return cell;
}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return  80;
    
}


- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

//上拉刷新
- (void)addheader
{
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        

       
        [self requestData];
        //这里的RefreshView就是footer
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
        //        NSLog(@"%@--->正在刷新", mainScroll.class);
    };
    
}
-(void)setNavi{

    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    
    self.title=@"储值记录";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];


}
-(void)tableHeaderView{
    
    tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,90/2)];
    tableHeaderView.backgroundColor= zuiqianhuiColor;
    table.tableHeaderView=tableHeaderView;
    
    UILabel*cardMoney=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 70, 45)];
    cardMoney.text=@"当前余额";
    cardMoney.font=[UIFont systemFontOfSize:15];
    [tableHeaderView addSubview:cardMoney];
    UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(0, 45-0.35, ScreenWidth, 0.35)];
    lineLabel1.backgroundColor=qianhuiColor;
    [tableHeaderView addSubview:lineLabel1];
    NSString*GoldPrice=[NSString stringWithFormat:@"%@",[dic objectForKey:@"cardMoney"]];
    UILabel*cardMoneyStr=[[UILabel alloc]initWithFrame:CGRectMake(cardMoney.right, 0, 180, 45)];
    cardMoneyStr.text=[NSString stringWithFormat:@"%@ 元",GoldPrice];
    cardMoneyStr.textColor=[UIColor blackColor];
    cardMoneyStr.font=[UIFont systemFontOfSize:15];
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ 元",  GoldPrice]];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:20]
     
                          range:NSMakeRange(0, [GoldPrice length])];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:[UIColor blackColor]
     
                          range:NSMakeRange(0, [GoldPrice length])];
    cardMoneyStr.attributedText = AttributedStr;
    
    [tableHeaderView addSubview:cardMoneyStr];
    
    
    UIButton*chongzhi=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-136/2-26/2, 6.5, 136/2, 33)];
    chongzhi.backgroundColor=luseColor;
    [chongzhi setTitle:@"充值" forState:UIControlStateNormal];
    [chongzhi setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    chongzhi .titleLabel.font=[UIFont systemFontOfSize:contenfot];
    [chongzhi addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [chongzhi.layer setCornerRadius:2.0]; //设置矩圆角半径
    [chongzhi.layer setBorderWidth:0.3];   //边框宽度
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){23/255.0, 148/255.0, 152/255.0, 1.0});
    [chongzhi.layer setBorderColor:tureBTncolorref];//边框颜色
    
    [tableHeaderView addSubview:chongzhi];
    
}


@end
